package com.eqdd.yiqidian.ui.companyspace

import android.app.Activity
import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector
import com.eqdd.yiqidian.base.BaseActivity
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.CompanyDemandBean
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonConverter
import com.eqdd.yiqidian.utils.TimeUtil
import com.lzy.okgo.OkGo
import com.lzy.okrx2.adapter.FlowableBody
import com.shizhefei.mvc.MVCCoolHelper
import io.reactivex.Flowable
import kotlinx.android.synthetic.main.activity_recyclerview_refresh.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import java.util.*

/**
 * Created by jhj on 18-7-10.
 */
class DemandListActivity : BaseActivity() {

    var mvcHelper: MVCCoolHelper<List<CompanyDemandBean>>? = null
    var type = 0
    var companyId = -1

    override fun initBinding() {
        setContentView(R.layout.activity_recyclerview_refresh)
        initTopTitleBar(View.VISIBLE, "需求列表")
        type = intent.getIntExtra(Config.TYPE, -1)
        if (type == 0) {
            initTopRightText("新增") {
                startActivityForResult<DemandAddActivity>(Config.ADD)
            }
        }
    }

    override fun initData() {
        var pageNum = 0
        val list = arrayListOf<CompanyDemandBean>()
        if (type == 0 || type == 1) {
            companyId = user.companyId
        } else {
            toast("获取信息失败")
            finish()
            return
        }
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.addItemDecoration(DividerLineItemDecoration(this))
        val slimAdapterEx = SlimAdapterEx.create().register<CompanyDemandBean>(R.layout.layout_list_demand, object : SlimInjector<CompanyDemandBean> {
            override fun onInject(data: CompanyDemandBean?, injector: IViewInjector<out IViewInjector<*>>?) {

                val array = data?.EndTime?.split("/", " ", ":", "-")
                val calendar = Calendar.getInstance()
                var status = ""
                array?.let {
                    if (it.size > 2) {
                        calendar.set(it[0].toInt(), it[1].toInt() - 1, it[2].toInt(), 23, 59, 59)
                    }
                    val a = calendar.timeInMillis
                    val b = Calendar.getInstance().timeInMillis

                    status = if (a > b) {
                        "（进行中）"
                    } else {
                        "（已结束）"
                    }
                }

                injector
                        ?.text(R.id.tv_demand_title, data?.ProductName)
                        ?.visibility(R.id.tv_demand_title, if (data?.ProductName.isNullOrBlank()) View.GONE else View.VISIBLE)
                        ?.text(R.id.tv_demand_time, String.format(Locale.CHINA, "发布时间：%s${status}", TimeUtil.formatWebTime1(data?.createTime)))
                        ?.text(R.id.tv_demand_label, String.format(Locale.CHINA, "产品描述：%s", data?.ProductDesc))
                        ?.visibility(R.id.tv_demand_label, if (data?.ProductDesc.isNullOrBlank()) View.GONE else View.VISIBLE)
                        ?.text(R.id.tv_demand_budget, String.format(Locale.CHINA, "需求预算：%s", data?.DemandPrice))
                        ?.visibility(R.id.tv_demand_budget, if (data?.DemandPrice.isNullOrBlank()) View.GONE else View.VISIBLE)
                        ?.text(R.id.tv_demand_count, String.format(Locale.CHINA, "需求量：%s", data?.DemandNum))
                        ?.visibility(R.id.tv_demand_count, if (data?.DemandNum.isNullOrBlank()) View.GONE else View.VISIBLE)
                        ?.text(R.id.tv_demand_address, String.format(Locale.CHINA, "发货地址：%s", data?.DemandAddress))
                        ?.visibility(R.id.tv_demand_address, if (data?.DemandAddress.isNullOrBlank()) View.GONE else View.VISIBLE)
            }
        }).attachTo(recyclerView).updateData(list as List<CompanyDemandBean>?) as SlimAdapterEx<CompanyDemandBean>?
        ItemClickSupport.addTo(recyclerView).setOnItemClickListener { recyclerView, position, v ->
            if (type == 0) {
                startActivity<ProDemandInfoActivity>(Config.ID to slimAdapterEx?.getDataItem(position)?.Id, Config.TYPE to 2, "fun" to 2)
            } else if (type == 1) {
                val bean = slimAdapterEx?.getDataItem(position)
                startActivityForResult<DemandMatchProductActivity>(1000, Config.ID to bean?.Id)
            }
        }


        val dataSource = ModelRx2DataSource<CompanyDemandBean>(ModelRx2DataSource.OnLoadSource<CompanyDemandBean> { page, register ->
            pageNum = if (page == 1) 0 else pageNum
            OkGo.post<HttpResult<List<CompanyDemandBean>>>(HttpConfig.BASE_URL + HttpConfig.DEMAND_LIST)
                    .params("companyId", companyId)
                    .params("page", pageNum)
                    .converter(object : JsonConverter<HttpResult<List<CompanyDemandBean>>>() {
                        override fun test() {
                            super.test()
                        }
                    }).adapt(FlowableBody<HttpResult<List<CompanyDemandBean>>>())
                    .flatMap({ result ->
                        if (page == 1) {
                            mvcHelper?.setAutoLoadMore(true)
                        }
                        pageNum = result.page
                        Flowable.just<MutableList<CompanyDemandBean>>(if (result.items == null) ArrayList() else result.items as MutableList<CompanyDemandBean>?)
                    })

        }, 10)
        mvcHelper = MVCCoolHelper<List<CompanyDemandBean>>(coolRefreshView)
        mvcHelper?.setDataSource(dataSource)
        mvcHelper?.adapter = slimAdapterEx
        mvcHelper?.refresh()
    }

    override fun setView() {

    }

    override fun onResume() {
        super.onResume()
        mvcHelper?.refresh()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                Config.ADD,
                Config.UPDATE -> {
                    mvcHelper?.refresh()
                }
            }
        }

    }
}